﻿const downloadArr = myArrStr.split(',');

let actorsBookArr = [];
let actorsBookMap = new Map();
let actorsCheckDateMap = new Map();
chrome.runtime.sendMessage({action: "getActorsBookmarks"}, bookmarks => {
    actorsBookArr = bookmarks.actorsBookArr;
    bookmarks.actorsBookMapArr.forEach(item => {
        let arr = item.split('@');
        actorsBookMap.set(arr[0], arr[1]);
        actorsCheckDateMap.set(arr[0], arr[2]);
    });
});
let seriesBookArr = [];
let seriesBookMap = new Map();
let seriesCheckDateMap = new Map();
chrome.runtime.sendMessage({action: "getSeriesBookmarks"}, bookmarks => {
    seriesBookArr = bookmarks.seriesBookArr;
    bookmarks.seriesBookMapArr.forEach(item => {
        let arr = item.split('@');
        seriesBookMap.set(arr[0], arr[1]);
        seriesCheckDateMap.set(arr[0], arr[2]);
    });
});
let actorsCountMap = new Map();
let seriesCountMap = new Map();
chrome.runtime.sendMessage({action: "getCountMapArr"}, result => {
    result.actorsCountMapArr.forEach(item => {
        let arr = item.split('@');
        actorsCountMap.set(arr[0], arr[1]);
    });
    result.seriesCountMapArr.forEach(item => {
        let arr = item.split('@');
        seriesCountMap.set(arr[0], arr[1]);
    });
});

window.onload = async function () {

    let movieList = await movieListFun(document);
    if (movieList !== undefined) console.log("movieList: " + movieList.length);

    updateBookmark(movieList);

    videoDetailFun();

    actorsFun();

    seriesFun();

};

function updateBookmark(movieList) {
    let pageNo = window.location.toString().includes('page') ? 2 : 1;
    let pathname = window.location.pathname;
    if (!pathname.includes('actors') && !pathname.includes('series')) return;

    let sectionElement;
    if (pathname.includes('actors')) sectionElement = document.querySelector(".actor-section-name");
    if (pathname.includes('series')) sectionElement = document.querySelector(".section-name");
    if (!movieList || movieList.length === 0) {
        sectionElement.style.color = 'red';
        sectionElement.innerHTML += ' [已收藏全部下载]';
        return;
    }

    let nameArr = sectionElement.innerHTML.split(', ');
    let param = pathname + ',' + pageNo + ',' + movieList[0].date + ',' + nameArr[0] + '@' + JSON.stringify(movieList);
    sectionElement.innerHTML +=
        '<button id="updateBookmark1" ' +
        'style="margin: 0 5px; font-size: inherit; background-color: greenyellow;">更新书签</button>' +
        '<button id="updateBookmark2" ' +
        'style="margin: 0 5px; font-size: inherit; background-color: greenyellow;">更新书签&自动打开</button>';
    document.getElementById('updateBookmark1').setAttribute('data-custom-param', param + '@' + '1');
    document.getElementById('updateBookmark1').addEventListener('click', buttonClick);
    document.getElementById('updateBookmark2').setAttribute('data-custom-param', param + '@' + '2');
    document.getElementById('updateBookmark2').addEventListener('click', buttonClick);
}

function buttonClick(event) {
    let customParamArr = event.target.dataset.customParam.split('@');
    console.log("buttonClick ===>> customParamArr", customParamArr);
    let paramArr = customParamArr[0].split(',');
    let movieList = JSON.parse(customParamArr[1]);
    let type = customParamArr[2];
    chrome.runtime.sendMessage({
        action: "updateBookmark",
        actors: paramArr[0],
        pageNo: paramArr[1],
        cDate: paramArr[2],
        type: type,
        movieList: movieList,
        bookName: paramArr[3] + ' ' + paramArr[2] + ' | JavDB ',
        bookUrl: window.location.toString()
    }, result => {
        if (!result || !result.key) return;
        console.log("更新当前书签：" + JSON.stringify(result));
        const today = getFormattedDate(new Date());
        if (result.key.includes('series')) {
            seriesBookMap.set(result.key, result.cDate);
            seriesCheckDateMap.set(result.key, today);
            console.log("更新当前书签：seriesBookMap", seriesBookMap.get(result.key), seriesBookMap);
        } else {
            actorsBookMap.set(result.key, result.cDate);
            actorsCheckDateMap.set(result.key, today);
            console.log("更新当前书签：actorsBookMap", actorsBookMap.get(result.key));
        }
    });
}

async function movieListFun(document) {
    let movieListElement = document.querySelector('.movie-list');
    if (!movieListElement) return;

    let pathname = window.location.pathname;
    // if (!pathname.includes('actors') && !pathname.includes('series')) return;

    let dateStr = '';
    if (pathname.includes('actors')) dateStr = actorsBookMap.get(pathname);
    if (pathname.includes('series')) dateStr = seriesBookMap.get(pathname);
    console.log("pathname" + pathname, "dateStr: " + dateStr);
    let oldDate = dateStr && dateStr.includes('-') ? new Date(dateStr) : new Date('1970-07-01');

    let movieList = [];
    movieListElement.querySelectorAll('.item').forEach(item => {
        let meta = item.querySelector(".meta");
        let cDateStr = meta.innerHTML.trim();
        let cDate = new Date(cDateStr);

        let videoTitle = item.querySelector('.video-title');
        let codeElement = videoTitle.querySelector("strong");
        let code = codeElement.innerHTML.trim();
        let aElement = item.querySelector("a");
        aElement.href += '?pathname=' + pathname + '&' + 'cDate=' + cDateStr;
        if (cDate > oldDate && !downloadArr.includes(code)) {
            videoTitle.style.color = "green";
            codeElement.style.color = "green";
            codeElement.innerHTML += "[更新]";
            if (!videoTitle.innerHTML.includes("VR")) movieList.push({
                href: aElement.href,
                date: meta.innerHTML.replaceAll(' ', '').replaceAll('\n', '')
            });
        } else {
            videoTitle.style.color = "red";
            codeElement.style.color = "red";
            codeElement.innerHTML += "[已下载]";
        }
    });

    let paginationNext = document.querySelector('.pagination-next');
    if (paginationNext) {
        await fetch(paginationNext.href)
            .then(response => response.text())
            .then(async html => {
                let newDocument = new DOMParser().parseFromString(html, 'text/html');
                let newMovieList = await movieListFun(newDocument);
                movieList = movieList.concat(newMovieList);
            });
    }
    return movieList;
}

function videoDetailFun(key) {
    let videoDetail = document.querySelector('.video-detail');
    if (!videoDetail) return;

    let codeElement = videoDetail.querySelector("strong");
    if (!codeElement) return;

    let code = codeElement.innerHTML.trim();
    if (code.includes('[已下载]')) return;

    let currentTitle = videoDetail.querySelector(".current-title");
    if (!currentTitle) return;

    let paramArr = window.location.search.replace('?', '').split('&');
    key = key ? key : paramArr[0].split('=')[1];
    // if (!key.includes('actors') && !key.includes('series')) return;
    let cDate = new Date(paramArr[1].split('=')[1]);

    let dateStr = '';
    if (key.includes('actors')) dateStr = actorsBookMap.get(key);
    if (key.includes('series')) dateStr = seriesBookMap.get(key);
    let oldDate = dateStr && dateStr.includes('-') ? new Date(dateStr) : new Date('1970-07-01');

    let checkDateStr = actorsCheckDateMap.get(key);
    let checkDate = new Date(checkDateStr);
    let newCheck = new Date().getTime() - checkDate.getTime() < 1000 * 60 * 5;

    if ((cDate > oldDate || newCheck) && !code.includes('[更新]')) {
        codeElement.innerHTML = code + "[更新]";
        codeElement.style.color = "green";
        currentTitle.style.color = "green";
    }
    if (cDate <= oldDate && !newCheck) {
        code = code.replace('[更新]', '')
        codeElement.innerHTML = code + "[已下载]";
        codeElement.style.color = "red";
        currentTitle.style.color = "red";
    }
}

function actorsFun() {
    let moviePanelInfo = document.querySelector('.movie-panel-info');
    if (!moviePanelInfo) return;

    let panelBlockList = moviePanelInfo.querySelectorAll(".panel-block");
    if (!panelBlockList) return;

    panelBlockList.forEach(panelBlock => {
        let strongElement = panelBlock.querySelector("strong");
        if (!strongElement) return;
        if (!strongElement.innerHTML.includes("演員")) return;

        let actorsElement = panelBlock.querySelector("span");
        actorsElement.querySelectorAll("a").forEach(aElement => {
            let href = aElement.href.replace('https://javdb.com', '');
            aElement.href += "?t=s,d&sort_type=0"
            if (!actorsBookArr.includes(href)) return;

            let count = actorsCountMap.get(href);
            aElement.style.color = count > 0 ? "green" : "red";
            aElement.innerHTML += count > 0 ? "[收藏有更新：" + count + "]" : "[已收藏]";

            videoDetailFun(href);
        });
    });
}

function seriesFun() {
    let moviePanelInfo = document.querySelector('.movie-panel-info');
    if (!moviePanelInfo) return;

    let panelBlockList = moviePanelInfo.querySelectorAll(".panel-block");
    if (!panelBlockList) return;

    panelBlockList.forEach(panelBlock => {
        let strongElement = panelBlock.querySelector("strong");
        if (!strongElement) return;
        if (!strongElement.innerHTML.includes("系列")) return;

        let seriesElement = panelBlock.querySelector("span");
        let aElement = seriesElement.querySelector("a");
        if (!aElement.href.includes('?f=download')) aElement.href += '?f=download';
        let href = aElement.href.split('?')[0].replace('https://javdb.com', '');
        if (!seriesBookArr.includes(href)) return;

        let count = seriesCountMap.get(href);
        aElement.style.color = (count && count > 0) ? "green" : "red";
        aElement.innerHTML += (count && count > 0) ? "[收藏有更新：" + count + "]" : "[已收藏]";

        videoDetailFun(href)
    });
}
